<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VSelect v-model="form.platform_ids" placeholder="绑定平台" :options="options.platform" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.shop_ids" placeholder="绑定店铺" :options="options.shop" multiple collapse-tags
          style="min-width: 160px" confusedPaste paste />
        <VSelect v-model="form.city_id" placeholder="号码地区" :options="options.city" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.phone_types" placeholder="号码类型" :options="options.phone_type" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.phone_statuses" placeholder="号码状态" :options="options.phone_status" multiple collapse-tags
          style="min-width: 160px" />
        <VSelect v-model="form.manager_ids" placeholder="管理人" :options="options.manager" multiple collapse-tags
          style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 120px">
            <el-option label="到期日期" value="expiry_date"></el-option>
          </el-select>
          <el-date-picker v-model="form.dateRange.value" type="daterange" value-format="YYYY-MM-DD" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" style="max-width: 260px" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="手机号码" value="phone_num"></el-option>
            <el-option label="绑定实体号" value="entity_num"></el-option>
          </el-select>
          <el-input v-model="form.input.value" placeholder="请输入" class="w-40" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/base/phone/create" type="primary" icon="DocumentAdd" @click="create(tableRef)">添加</VButton>
        <VButton auth="/base/phone/delete" @click="handleBatch('delete')">删除</VButton>
        <VButton auth="/base/phone/edit" @click="handleBatch('phoneStatus')">修改号码状态</VButton>
        <VImport :tableRef="tableRef" importUrl="/v1/phone/import"
                 v-if="authList.includes('/base/phone/import')"
          downloadUrl="https://xc-base.oss-cn-shenzhen.aliyuncs.com/template/phone.xlsx" class="ml-auto" />
        <VExport auth="/base/phone/export" mainKey="phone_id" name="phone" :tableRef="tableRef" task />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <PhoneStatus ref="phoneStatusRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <Bind ref="bindRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import Bind from './components/Bind'
import PhoneStatus from './components/PhoneStatus'
import VImport from '@/components/VImport'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'

const baseName = 'phone'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
const authList = window.BTN_AUTH || []
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const phoneStatusRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const phone_ids = selection.map(d => d.phone_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ phone_ids }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    phoneStatus: () => {
      phoneStatusRef?.value.open(phone_ids)
    }
  }
  handle[name]()
}
// 单行操作
const bindRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { phone_id } = row
  const showLoading = (name = 'handle') => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = (name = 'handle') => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    edit: () => {
      addRef?.value.open(phone_id)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ phone_ids: [phone_id] }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    bind: () => {
      bindRef?.value.open(phone_id)
    },
    log: () => {
      logRef?.value.open({ type: baseName, record_id: phone_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'phone_num', value: '' }, // 组合
      dateRange: { type: 'expiry_date', value: [], range: true }, // 组合
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    { type: 'seq', fixed: 'left', width: 50, slots: { header: () => '序号' } },
    { title: '手机号码', field: 'phone_num', minWidth: 140, sortable: true },
    { title: '号源', field: 'phone_source', minWidth: 140, sortable: true },
    { title: '号码地区', field: 'phone_area_names', minWidth: 140, sortable: true },
    { title: '号码类型', field: 'phone_type', minWidth: 140, sortable: true },
    { title: '绑定实体号', field: 'entity_num', minWidth: 140, sortable: true },
    {
      title: '号码状态', field: 'phone_status', minWidth: 140, sortable: true, slots: {
        default: ({ row }) => <VStatus status={row.phone_status==='正常'} true-label='正常' false-label='失效' />
      }
    },
    // {
    //   title: '自动续费状态', field: 'aaa', minWidth: 140, slots: {
    //     default: ({ row }) => <VStatus status={row.aaa} line={2} />
    //   }
    // },
    { title: '认证状态', field: 'auth_status', minWidth: 120, sortable: true },
    { title: '可用天数', field: 'available_days', minWidth: 120, sortable: true },
    {
      title: '到期时间', field: 'expiry_date', minWidth: 170, sortable: true
    },
    {
      title: '关联店铺', field: 'assoc_shops', minWidth: 100, sortable: true, slots: {
        default: ({ row }) => row.assoc_shops ? (authList.includes('/base/phone/shop-list') ? <el-button link type='primary' onClick={() => handleRow('bind', row)}>{row.assoc_shops}</el-button> : row.assoc_shops) : 0
      }
    },
    {
      title: '管理负责人', field: 'manager_name', minWidth: 120, sortable: true, slots: {
        default: ({ row }) => <VText value={row.manager_name} line={2} />
      }
    },
    {
      title: '备注', field: 'remark', minWidth: 120, slots: {
        default: ({ row }) => <VText value={row.remark} line={2} />
      }
    },
    {
      title: '操作', width: 110, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          return <div class='nm flex flex-wrap gap-1'>
            <VButton auth="/base/phone/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton>
            <VButton auth="/base/phone/delete" link type="danger" onClick={() => handleRow('delete', row, rowIndex)}>删除</VButton>
            <VButton auth="/base/phone/log" link type="primary" onClick={() => handleRow('log', row)} class='m-0'>日志</VButton>
          </div>
        }
      }
    }
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  